package com.cci.kangdao.azureBlob;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.blob.*;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 将文件上传到微软云存储账号
 * @Company: CTY
 * @author myc
 * @date 2018-02-23
 * @version 1.0
 */
public class AzureBlobTool {
	private static Logger log = Logger.getLogger(AzureBlobTool.class);
//	public static final String storageConnectionString ="DefaultEndpointsProtocol=https;"
//			+ "AccountName=myc;"
//			+ "AccountKey=4SowZY8v364JH1fB+XNmzZQlhGM09rQkQVNEzt92y9vBYjCItDBCDaj5Uc4mpn6OtnM6IgpsfqxioKdSiKX5jA==;"
//			+ "EndpointSuffix=core.chinacloudapi.cn";

	/**
	 * 文件上传到微软云
	 * @param blobConnection 连接串
	 * @param containerName 容器
	 * @param filePath 文件路径
	 * @return
	 */
	public static String uploadBlob(String accountName,String blobConnection,String containerName,String filePath){
		
		File sourceFile = null;
		CloudStorageAccount storageAccount;
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		try{
			/**
			 * 创建连接，并打开容器
			 * 容器名只能小写
			 */
//			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			storageAccount = CloudStorageAccount.parse(blobConnection);
			blobClient = storageAccount.createCloudBlobClient();
			container = blobClient.getContainerReference(containerName.toLowerCase());

			/**
			 * 如果容器没有公众访问，则创建容器
			 */
			container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());

			
			sourceFile = new File(filePath);
			CloudBlockBlob blob = container.getBlockBlobReference(sourceFile.getName());
			
			/**
			 * 必须设置头文件，要么会直接现在
			 * 关于ContentType 的值可以参考网络资料：https://www.cnblogs.com/icon/p/3680640.html
			 */
			if(filePath.toLowerCase().endsWith(".jpe") || filePath.toLowerCase().endsWith(".jpeg") || filePath.toLowerCase().endsWith(".jpg")){
				blob.getProperties().setContentType("image/jpeg");
				
			}else if(filePath.toLowerCase().endsWith(".png")){
				blob.getProperties().setContentType("image/png");
				
			}else if(filePath.toLowerCase().endsWith(".pdf")){
				blob.getProperties().setContentType("application/pdf");
				
			}else if(filePath.toLowerCase().endsWith(".mp4")){
				blob.getProperties().setContentType("video/mp4");
			}
			
					
			
//			//创建路径
//			CloudBlobDirectory d = container.getDirectoryReference("a");	
//			CloudBlobDirectory d1 = d.getDirectoryReference("b");
//			CloudBlobDirectory d2 = d1.getDirectoryReference("c");
//			CloudBlockBlob blob = d2.getBlockBlobReference(sourceFile.getName());			


//			BlobProperties props = blob.getProperties();
//			props.setContentMD5("");
//			blob.getProperties().(metadata);
			blob.getProperties().setContentMD5("");
			BlobRequestOptions requestOptions = new BlobRequestOptions();
			requestOptions.setDisableContentMD5Validation(true);
			requestOptions.setStoreBlobContentMD5(true);
					
			/**
			 * 创建blob并上传文件到blob		
			 */
			blob.uploadFromFile(filePath);

//			return "https://myc.blob.core.chinacloudapi.cn/"+containerName.toLowerCase()+"/"+sourceFile.getName();
			String fileName =  sourceFile.getName();
			fileName = fileName.replace("\\", "/");
			return "https://"+accountName+".blob.core.chinacloudapi.cn/"+containerName.toLowerCase()+"/"+fileName;
		}catch (Exception e) {
			log.error(e.getMessage(),e);
		}finally{	
//			删除原文件
			if(sourceFile != null)
				sourceFile.deleteOnExit();
		}
		return null;
	}

	public static String uploadBlob(String accountName,String blobConnection,String containerName,String filePath,String folder){

		File sourceFile = null;
		CloudStorageAccount storageAccount;
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		try{
			/**
			 * 创建连接，并打开容器
			 * 容器名只能小写
			 */
//			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			storageAccount = CloudStorageAccount.parse(blobConnection);
			blobClient = storageAccount.createCloudBlobClient();
			container = blobClient.getContainerReference(containerName.toLowerCase());

			/**
			 * 如果容器没有公众访问，则创建容器
			 */
			container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());


			sourceFile = new File(filePath);
			CloudBlockBlob blob = container.getBlockBlobReference(folder+sourceFile.getName());

			/**
			 * 必须设置头文件，要么会直接现在
			 * 关于ContentType 的值可以参考网络资料：https://www.cnblogs.com/icon/p/3680640.html
			 */
			if(filePath.toLowerCase().endsWith(".jpe") || filePath.toLowerCase().endsWith(".jpeg") || filePath.toLowerCase().endsWith(".jpg")){
				blob.getProperties().setContentType("image/jpeg");

			}else if(filePath.toLowerCase().endsWith(".png")){
				blob.getProperties().setContentType("image/png");

			}else if(filePath.toLowerCase().endsWith(".pdf")){
				blob.getProperties().setContentType("application/pdf");

			}else if(filePath.toLowerCase().endsWith(".mp4")){
				blob.getProperties().setContentType("video/mp4");
			}



//			//创建路径
//			CloudBlobDirectory d = container.getDirectoryReference("a");
//			CloudBlobDirectory d1 = d.getDirectoryReference("b");
//			CloudBlobDirectory d2 = d1.getDirectoryReference("c");
//			CloudBlockBlob blob = d2.getBlockBlobReference(sourceFile.getName());


//			BlobProperties props = blob.getProperties();
//			props.setContentMD5("");
//			blob.getProperties().(metadata);
			blob.getProperties().setContentMD5("");
			BlobRequestOptions requestOptions = new BlobRequestOptions();
			requestOptions.setDisableContentMD5Validation(true);
			requestOptions.setStoreBlobContentMD5(true);

			/**
			 * 创建blob并上传文件到blob
			 */
			blob.uploadFromFile(filePath);

//			return "https://myc.blob.core.chinacloudapi.cn/"+containerName.toLowerCase()+"/"+sourceFile.getName();
			String fileName =  sourceFile.getName();
			fileName = fileName.replace("\\", "/");
			return "https://"+accountName+".blob.core.chinacloudapi.cn/"+containerName.toLowerCase()+"/"+folder +fileName;
		}catch (Exception e) {
			log.error(e.getMessage(),e);
		}finally{
//			删除原文件
			if(sourceFile != null)
				sourceFile.deleteOnExit();
		}
		return null;
	}
	
	/**
	 * 删除微软云的文件
	 * @param blobConnection 连接串
	 * @param containerName 容器
	 * @param filename 文件名
	 * @return
	 */
	public static boolean deleteBlob(String blobConnection,String containerName,String filename){
		
		CloudStorageAccount storageAccount;
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		try{
			/**
			 * 创建连接，并打开容器
			 * 容器名只能小写
			 */
//			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			storageAccount = CloudStorageAccount.parse(blobConnection);
			blobClient = storageAccount.createCloudBlobClient();
			container = blobClient.getContainerReference(containerName.toLowerCase());
			
			CloudBlockBlob blob = container.getBlockBlobReference(filename);
			if ( blob.deleteIfExists() ) {
				return true;
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return false;
	}
	
	/**
	 * 获取微软云的文件
	 * @param blobConnection 连接串
	 * @param containerName 容器
	 * @return
	 */
	public static List<String> getListBlob(String blobConnection,String containerName){
		CloudStorageAccount storageAccount;
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		List<String> list = new ArrayList<String>();
		try{
			/**
			 * 创建连接，并打开容器
			 */
//			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			storageAccount = CloudStorageAccount.parse(blobConnection);
			blobClient = storageAccount.createCloudBlobClient();
			container = blobClient.getContainerReference(containerName.toLowerCase());
			/**
			 * 查询列表
			 */			
			for (ListBlobItem blobItem : container.listBlobs()) {
				list.add(blobItem.getUri().toString());
			}			
		}catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return list;
	}
	
	
	public static void main(String[] args){

	}
}
